package com.validator.plus.aop;

import com.validator.plus.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.PostConstruct;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @PostConstruct
    void init() {
        log.info("init GlobalExceptionHandler");
    }


    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ReturnT handleConstraintViolationException(ConstraintViolationException e) {
        String detail = e.getConstraintViolations().stream().map(it -> it.getPropertyPath() + ":" + it.getMessage()).collect(Collectors.joining(","));
        return ReturnT.error(detail);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ReturnT handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String detail = e.getBindingResult().getFieldErrors().stream().map(it -> it.getField() + ":" + it.getDefaultMessage()).collect(Collectors.joining(","));
        return ReturnT.error(detail);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ReturnT handleThrowable(BindException e) {
        String detail = e.getBindingResult().getFieldErrors().stream().map(it -> it.getField() + ":" + it.getDefaultMessage()).collect(Collectors.joining(","));
        return ReturnT.error(detail);
    }



}
